package com.glela.serial.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.glela.common.model.ProductTag;
import com.glela.common.util.DateUtil;
import com.glela.goods.mapper.GoodsMapper;
import com.glela.goods.mapper.ShareGoodsMapper;
import com.glela.goods.model.GoodsPrice;
import com.glela.goods.model.ShareGoods;
import com.glela.goods.model.vo.goods.GoodSerialVo;
import com.glela.goods.service.GoodsService;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.model.User;
import com.glela.platform.model.UserInfo;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.UserService;
import com.glela.serial.mapper.TitleDiscoveryMapper;
import com.glela.serial.mapper.TitleDiscoveryProductMapper;
import com.glela.serial.model.DiscoveryGoodVo;
import com.glela.serial.model.TitleDiscovery;
import com.glela.serial.model.TitleDiscoveryProduct;
import com.glela.serial.service.TitleDiscoveryProductService;


@Service("titleDiscoveryProductService")
public class TitleDiscoveryProductServiceImpl implements TitleDiscoveryProductService {
	private static Logger logger = LoggerFactory.getLogger(TitleDiscoveryProductServiceImpl.class);

	@Autowired
	private TitleDiscoveryProductMapper titleDiscoveryProductMapper;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private TitleDiscoveryMapper titleDiscoveryMapper;
	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private UserService userService;
	@Autowired
	private BaseRestrictionsService  baseRestrictionsService;
	@Autowired
	private ShareGoodsMapper shareGoodsMapper;
	
	@Override
	public List<TitleDiscoveryProduct> selectAllDiscoveryProductByTitleId(TitleDiscoveryProduct request) {
//		logger.info("begin------selectAllDiscoveryProductByTitleId-------impl");
		List<TitleDiscoveryProduct> list = this.titleDiscoveryProductMapper.selectAll1(request.getTitleId().toString());
		//获取用户信息
//		User user = null ;
//		if (null != request.getUserId() && request.getUserId() > 0) {
//			user = userMapper.selectByPrimaryKey(request.getUserId());
//		}
		// 店主用户ID  默认是校妆姐姐店铺的店主ID
		Integer storeUserId = this.baseRestrictionsService.getBaseRestrictionsForCache("xz_jj").getExperience();
		User user = null;//登录用户
//		if (null != request.get("userId") && Long.parseLong(request.get("userId").toString())> 0) {
//			user = this.userService.getUser(Long.parseLong(request.get("userId").toString()));
		if (null != request.getUserId() && request.getUserId()> 0) {
			user = this.userService.getUser(request.getUserId());
//			int roleId = 0;
			if(user!=null && user.getRecommendFrom()!=null){
//				roleId = user.getRoleId();
				//登录人对应的店主身份ID
				String recommendFrom = user.getRecommendFrom();
				UserInfo userInfo = this.userService.selectUserInfoByPersionId(recommendFrom);//推荐人身份
				if(userInfo!=null){
					storeUserId = Integer.parseInt(userInfo.getUserId()+"");		
				}
			}
		}
		User u = this.userMapper.selectByPrimaryKey(Long.valueOf(storeUserId));//使用推荐人去计算价格（默认校妆姐姐）
		if (!list.isEmpty()) {
			TitleDiscovery titleDiscovery = this.titleDiscoveryMapper.selectByPrimaryKey(list.get(0).getTitleId());
			for (TitleDiscoveryProduct titleDiscoveryProduct : list) {
				//发现标题、长标题、喜欢人数、图片
                titleDiscoveryProduct.setSharePic(titleDiscovery.getSharePic());
                titleDiscoveryProduct.setShareContent(titleDiscovery.getShareContent());
				titleDiscoveryProduct.setTitleName(titleDiscovery.getTitle());
				titleDiscoveryProduct.setLongTitleName(titleDiscovery.getLongTitle());
				titleDiscoveryProduct.setLikeTotalCount(titleDiscovery.getLikeTotalCount());
				titleDiscoveryProduct.setTitlePic(titleDiscovery.getTitlePic());
				List<DiscoveryGoodVo> gList = new ArrayList<DiscoveryGoodVo>();
				if ( !StringUtils.isEmpty(titleDiscoveryProduct.getGoodsId()) && !titleDiscoveryProduct.getGoodsId().equals("0") ) {
					String[] gId = titleDiscoveryProduct.getGoodsId().split(",");
					for (String id : gId) {
						Map<String, Object> params = new HashMap<>();
						params.put("product_sn", id);
						params.put("current_time", new Date());
//						DiscoveryGoodVo vo = new DiscoveryGoodVo();
//						if (StringUtils.isNotEmpty(request.getFrom())) {//通过分享链接打开需要添加分享记录id参数
//							Long talentShareGoodId = this.addShareGoods(user.getId(), Long.parseLong(id));
//							vo.setTalentShareGoodId(talentShareGoodId);
//						}
//						vo.setGoodId(Long.parseLong(id));
						//商品信息
						GoodSerialVo g =  this.goodsService.selectOneGoodById(Long.parseLong(id));
						if (null != g) {//商品未下架才返回
							DiscoveryGoodVo vo = new DiscoveryGoodVo();
							if (StringUtils.isNotEmpty(request.getFrom())) {//通过分享链接打开添加分享记录id参数
//							if (null != request.get("from") && StringUtils.isNotEmpty(request.get("from").toString())){//通过分享链接打开添加分享记录id参数
								Long talentShareGoodId = this.addShareGoods(user.getId(), Long.parseLong(id));
								vo.setTalentShareGoodId(talentShareGoodId);
							}
							vo.setGoodId(g.getGoodId());
							vo.setLabelName(g.getLabelName());
							vo.setName(g.getName());
							vo.setNavigateImage(g.getNavigateImage());
							//商品价格
							GoodsPrice goodsViewPriceForProduct = null;
							try {
//								goodsViewPriceForProduct = goodsService.getGoodsViewPriceForGoods(user, Long.parseLong(id));
								goodsViewPriceForProduct = goodsService.getGoodsViewPriceForGoods(u, Long.parseLong(id));
							} catch (Exception e) {
								e.printStackTrace();
							} 
							if (null != goodsViewPriceForProduct) {
								vo.setLowestPrice(goodsViewPriceForProduct.getSalePrice());
								vo.setSuggestedPrice(goodsViewPriceForProduct.getMarketPirce());
							}else {//没有规格，不返回该商品
								continue;
							}
							//商品标签
							List<ProductTag> ptList = new ArrayList<ProductTag>();
//							List<LimitTimeSaleDetail> limitList = limitTimeSaleDetailMapper.selectByGoodsId(params);
//							if (null != limitList && !limitList.isEmpty()) {//特卖中
//								p.setLabel("特卖");
//							}else{
//								if (g.getSelfSupport() == 0) {
//									p.setLabel("自营");
//								}else if(g.getSelfSupport() == 1) {
//									p.setLabel("非自营");
//								}
//							}
							String nowTime = DateUtil.currentStringDate();
							//状态
							Map<String,Object> ltsMap = this.goodsMapper.selectNearlyLimitTimeSale(Long.parseLong(id),goodsViewPriceForProduct.getProductId(),nowTime);
							if(ltsMap != null){
								ProductTag p = new ProductTag();
								p.setColor("#ff4b7a");
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//抢购开始时间
								try {
									Date fullBeginTime = sdf.parse(ltsMap.get("fullBeginTime").toString());
									// 系统当前时间
									long nowTimeMillis = System.currentTimeMillis();
									if (fullBeginTime.getTime() > nowTimeMillis) {// 预热中
										p.setLabel("预热");
									} else {
										p.setLabel("特卖");
									}
								} catch (Exception e) {
									
								}
								ptList.add(p);
							}
							//属性
							if (g.getSelfSupport() == 0) {
								ProductTag pT = new ProductTag();
								pT.setColor("#ff4b7a");
								pT.setLabel("自营");
								ptList.add(pT);
							}
//							else if(g.getSelfSupport() == 1) {
//								pT.setLabel("非自营");
//							}
							vo.setProductTags(ptList);
							gList.add(vo);
						}
					}
				}
				titleDiscoveryProduct.setGoodsDetail(gList);
			}
		}
		return list;
	}
	/** 
	* @Title: addShareGoods 
	* @Description: 获取用户分享商品的记录ID（如果没有分享就新增一条分享记录）
	* @param @param userId
	* @param @param goodId
	* @param @return    设定文件 
	* @return Long    返回类型    分享记录ID
	* @throws 
	* @author zhangrenjie
	* @date 2017年8月16日 上午11:38:40 
	*/
	public Long addShareGoods(long userId, long goodId) {
		ShareGoods shareGoods = shareGoodsMapper.selectShareGoodsByUserIdAndGoodIdAndAgio(userId, goodId);
		Long talentShareGoodId = null ;
		if (shareGoods == null) {
			shareGoods = new ShareGoods();
			shareGoods.setUserId(userId);
			shareGoods.setGoodId(goodId);
			shareGoodsMapper.insertShareGoods(shareGoods);
			//添加成功 goods表分享次数+1
			this.goodsMapper.saveOpenAndShareCount(Integer.valueOf(goodId+""), 0, 1);
			talentShareGoodId = shareGoods.getId() ;
		} 
		if (shareGoods != null) {
			talentShareGoodId = shareGoods.getId() ;
		}
		return talentShareGoodId;
	}
	

}
